﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using ConfigurationManager.View.Dialog;

namespace ConfigurationManager.View
{
    public partial class frmProcessList : Form
    {
        List<Model.Process> _processes;
        List<Model.Product> _products;
        List<Model.Instance> _instances;
        List<Model.InteligenceModule> _inteligenceModules;

        public frmProcessList()
        {
            InitializeComponent();
            this.dtgProcesses.AutoGenerateColumns = false;
            this.Load += new EventHandler(frmProcessList_Load);
        }

        void frmProcessList_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;

            LoadProcesses();

            PopulateProductCombo();
        }

        private void PopulateProductCombo()
        {
            cboProduct.DisplayMember = "Name";
            cboProduct.ValueMember = "Id";
            cboProduct.Items.Add(new Model.Product()
                {
                    Id = 0,
                    Name = string.Empty
                });
            foreach (Model.Product p in _products)
            {
                cboProduct.Items.Add(p);
            }
        }

        private void LoadProcesses()
        {
            _processes = Model.Process.Retrieve();
            LoadAuxData();

            PopulateProcessesGrid();
        }

        private void LoadAuxData()
        {
            _products = Model.Product.Retrieve();
            _instances = Model.Instance.Retrieve();
            _inteligenceModules = Model.InteligenceModule.Retrieve();
        }

        private void PopulateProcessesGrid()
        {
            if (cboProduct.SelectedIndex > 0)
            {
                List<Model.Process> processes = _processes.FindAll(p => p.Instance.Product.Id == ((Model.Product)cboProduct.SelectedItem).Id);
                dtgProcesses.DataSource = processes;
            }
            else
                dtgProcesses.DataSource = _processes;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadProcesses();
        }

        private void dtgProcesses_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            if (dtgProcesses.Rows[e.RowIndex].Cells[e.ColumnIndex] == dtgProcesses.Rows[e.RowIndex].Cells["Edit"])
                EditProcess((Model.Process)dtgProcesses.Rows[e.RowIndex].DataBoundItem);
            else if (dtgProcesses.Rows[e.RowIndex].Cells[e.ColumnIndex] == dtgProcesses.Rows[e.RowIndex].Cells["Delete"])
                DeleteProcess((Model.Process)dtgProcesses.Rows[e.RowIndex].DataBoundItem);
        }

        private void dtgProcesses_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            EditProcess((Model.Process)dtgProcesses.Rows[e.RowIndex].DataBoundItem);
        }

        private void DeleteProcess(ConfigurationManager.Model.Process process)
        {
            try
            {
                int id;
                string name;
                id = process.Id;
                name = process.Name;
                if (MessageBox.Show(string.Format("Confirma a exclusão do processo {0} - {1}?", id, name), "Confimar Exclusão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Model.Process.Delete(process.Id, process.Instance.Product.Id);
                    MessageBox.Show("Processo excluído com sucesso!", "Process Manager Configuration", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadProcesses();
                }
            }
            catch (ValidationException ex)
            {
                MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                //EventLog.WriteEntry("Process Manager - Configuration Manager", ex.ToString(), EventLogEntryType.Error);
                //MessageBox.Show("Ocorreu um erro interno, verifique o event viewer para maiores detalhes");
                Program.HandleException(ex);
            }
        }

        private void EditProcess(ConfigurationManager.Model.Process process)
        {
            LoadAuxData();

            frmProcess addProcess = new frmProcess(_products, _instances, _inteligenceModules, process);
            addProcess.Owner = this;
            if (addProcess.ShowDialog() == DialogResult.OK)
                LoadProcesses();
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            LoadAuxData();

            frmProcess addProcess = new frmProcess(_products, _instances, _inteligenceModules);
            addProcess.Owner = this;
            if (addProcess.ShowDialog() == DialogResult.OK)
                LoadProcesses();
        }

        private void cboProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulateProcessesGrid();
        }
    }
}
